package com.rockcent.mall.lib.helper;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Response;
import com.rockcent.mall.lib.domain.MerchantOrderLogisticsLog;
import com.rockcent.mall.lib.repository.MarketOrderRepository;
import com.rockcent.mall.lib.repository.MerchantOrderLogisticsLogRepository;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by Marco on 16-11-11.
 */
@Component
public class MallOrderLogisticsHelper {

    private static Logger logger = LoggerFactory.getLogger(MallOrderLogisticsHelper.class);

    public static final String KEY = "WZehRTUd411";

    public static final String CUSTOMER = "F9A1159DF15F39DB1CDC498DA66471F5";

    public static final String POLLURL = "http://poll.kuaidi100.com/poll/query.do";

    @Autowired
    private AsyncHttpClient asyncHttpClient;

    @Autowired
    private MerchantOrderLogisticsLogRepository merchantOrderLogisticsLogRepository;

    @Autowired
    MarketOrderRepository marketOrderRepository;

    public String getLogisticsResponse(String logisticsCode, String logisticsNumber) throws Exception {
        String customer = MallOrderLogisticsHelper.CUSTOMER;
        String param ="{\"com\":\""+logisticsCode+"\",\"num\":\""+logisticsNumber+"\"}";
        String sign = DigestUtils.md5Hex(param+MallOrderLogisticsHelper.KEY+customer).toUpperCase();
        AsyncHttpClient.BoundRequestBuilder boundRequestBuilder = asyncHttpClient.preparePost(MallOrderLogisticsHelper.POLLURL);
        boundRequestBuilder.addParameter("customer", customer);
        boundRequestBuilder.addParameter("sign", sign);
        boundRequestBuilder.addParameter("param", param);
        ListenableFuture<Response> responseListenableFuture = boundRequestBuilder.execute();
        Response response = responseListenableFuture.get();
        String body = response.getResponseBody();
        return StringUtils.isBlank(body)?"":convertUtf8(body);
    }

    /**
     * json转化成map
     * @param jsonStr
     * @return
     */
    public Map<String, Object> parseJSON2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        //最外层解析
        JSONObject json = JSONObject.fromObject(jsonStr);
        for(Object k : json.keySet()){
            Object v = json.get(k);
            //如果内层还是数组的话，继续解析
            if(v instanceof JSONArray){
                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
                Iterator<JSONObject> it = ((JSONArray)v).iterator();
                while(it.hasNext()){
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

    public String convertUtf8(String str) throws Exception {
        return new String(str.getBytes("ISO-8859-1"),"UTF-8");
    }

    /**
     * 更新订单物流信息与订单状态
     * @param map
     * @throws Exception
     */
    public void updateOrderLogisticsAndMarketOrder(Map<String, Object> map) throws Exception {
        if(map!=null) {
            String orderNum = (String) map.get("orderNum");
            String remark = (String) map.get("remark");
            String sourceType = (String) map.get("sourceType");
            String status = (String) map.get("status");
            Long merchantId = (Long)map.get("merchantId");
            Long customerId = (Long)map.get("customerId");

            MerchantOrderLogisticsLog merchantOrderLogisticsLog = new MerchantOrderLogisticsLog();
            merchantOrderLogisticsLog.setOrderNum(orderNum);//订单号
            merchantOrderLogisticsLog.setRemark(remark);//备注
            merchantOrderLogisticsLog.setSourceType(sourceType);//来源
            merchantOrderLogisticsLog.setStatus(status);//状态
            merchantOrderLogisticsLog.setDateQuery(new Date());
            if(merchantId!=null) {
                merchantOrderLogisticsLog.setMerchantId(merchantId);
            }
            if(customerId!=null) {
                merchantOrderLogisticsLog.setCustomerId(customerId);
            }
            merchantOrderLogisticsLogRepository.save(merchantOrderLogisticsLog);
        }
    }

}
